<?php
/**
 * I-Cafe framework
 * 
 * @category CF
 * @package CF_Db
 * @link http://www.i-cafe.org
 * @license http://www.i-cafe.org/license
 * @version 04-04-2010
 * @author tcl_java@yahoo.com
 */

/**
 * 
 */
class CF_Db_Expr extends CF_Component
{
	/**
	 * @var string
	 */
	protected $_expr;
	
	/**
	 * 
	 * @param string $expr
	 * @param arrat $data [optional]
	 * @return void
	 */
	public function __construct($expr)
	{
		$data = func_get_args();
		array_shift($data);
		# notify before construct event
		$this->fireEvent('beforeconstruct', array($this, &$expr, &$data));
		
		# register events
		$this->addEvents(
			'beforebuild',
			'build'
		);

		//if(!is_array($data)) $data = array($data);
		$data = CF_Db::getInstance()->quote($data);
		
		foreach ($data as &$item){
			if(is_array($item)) $item = implode(',', $item);
		}
		
		$this->_expr = vsprintf($expr, $data);
		
		# notify construct event
		$this->fireEvent('construct', array($this, &$this->_expr, &$data));
	}
	
	/**
	 * 
	 * @return string
	 */
	public function __toString()
	{
		# notify before buil event
		if(CF_Observable::VALUE_RETURN === $this->fireEvent('beforebuild', array($this))) return;
		
		$res = $this->_expr;
		
		# notify build event
		$this->fireEvent('build', array($this, &$res));
		
		return $res;
	}
}
